import { useState } from 'react';
import * as ImageManipulator from 'expo-image-manipulator';
import { Alert } from 'react-native';
import { CropArea, ImageLayout, ImageSize, Offset } from '../components/imageEditor/types';

interface CropImageParams {
  imagePath: string;
  cropArea: CropArea | null;
  imageLayout: ImageLayout | null;
  imageSize: ImageSize | null;
  scale?: number;
  offset?: Offset;
  format?: ImageManipulator.SaveFormat;
  compress?: number;
}

/**
 * 图片裁剪Hook
 * 封装了使用ImageManipulator进行图片裁剪的逻辑
 */
const useCropImage = () => {
  const [isLoading, setIsLoading] = useState(false);

  /**
   * 执行图片裁剪
   * @param params 裁剪参数
   * @returns 裁剪后的图片结果
   */
  const cropImage = async (params: CropImageParams): Promise<ImageManipulator.ImageResult | null> => {
    const {
      imagePath,
      cropArea,
      imageLayout,
      imageSize,
      scale = 1,
      offset = { x: 0, y: 0 },
      format = ImageManipulator.SaveFormat.JPEG,
      compress = 1
    } = params;

    // 验证必要参数
    if (!cropArea || !imageLayout || !imageSize) {
      console.error('裁剪参数不完整');
      return null;
    }

    setIsLoading(true);

    try {
      // 计算原始图片和显示区域的比例因子
      const scaleX = imageSize.width / imageLayout.width;
      const scaleY = imageSize.height / imageLayout.height;
      
      // 计算裁剪框相对于图片的位置（考虑用户的缩放和平移）
      const relativeX = (cropArea.x - imageLayout.x - offset.x) / scale;
      const relativeY = (cropArea.y - imageLayout.y - offset.y) / scale;
      const relativeWidth = cropArea.width / scale;
      const relativeHeight = cropArea.height / scale;
      
      // 将相对坐标转换为原始图片上的像素坐标
      const cropParams = {
        originX: Math.max(0, Math.round(relativeX * scaleX)),
        originY: Math.max(0, Math.round(relativeY * scaleY)),
        width: Math.min(imageSize.width, Math.round(relativeWidth * scaleX)),
        height: Math.min(imageSize.height, Math.round(relativeHeight * scaleY))
      };
      
      // 确保裁剪区域在图片范围内
      cropParams.originX = Math.max(0, Math.min(imageSize.width - 1, cropParams.originX));
      cropParams.originY = Math.max(0, Math.min(imageSize.height - 1, cropParams.originY));
      cropParams.width = Math.min(cropParams.width, imageSize.width - cropParams.originX);
      cropParams.height = Math.min(cropParams.height, imageSize.height - cropParams.originY);
      
      // 应用裁剪
      const result = await ImageManipulator.manipulateAsync(
        imagePath,
        [{ crop: cropParams }],
        { compress, format }
      );

      return result;
    } catch (error) {
      console.error('裁剪失败:', error);
      Alert.alert('裁剪失败', '请重试');
      return null;
    } finally {
      setIsLoading(false);
    }
  };

  return {
    cropImage,
    isLoading
  };
};

export default useCropImage;